package com.faiz.algorithm;

public class SortList {
    public ListNode sortList(ListNode head) {
        ListNode tmp = head, tail = null;
        while (tmp != null && tmp.next != null) {
            tmp = tmp.next;
        }
        tail = tmp;
        return sortList(head, tail);
    }

    // 对链表进行归并排序
    private ListNode sortList(ListNode head, ListNode tail) {
        // base case
        if (head == tail) return head;

        ListNode median = getMedian(head, tail);

        ListNode leftHalf = sortList(head, median);

        ListNode rightHalf = sortList(median.next, tail);
        // 解除关联关系
        median.next = null;

        return mergeList2(leftHalf, rightHalf);
    }

    // 使用常规思路
    private ListNode mergeList2(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode tmp = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                tmp.next = l1;
                l1 = l1.next;
            } else {
                tmp.next = l2;
                l2 = l2.next;
            }
            tmp = tmp.next;
        }
        tmp.next = l1 == null ? l2 : l1;
        return dummy.next;
    }

    // 递归合并两个链表
    private ListNode mergeList(ListNode l1, ListNode l2) {
        // 递归合并两个链表
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }

        ListNode head = null;

        if (l1.val < l2.val) {
            head = l1;
            head.next = mergeList(l1.next, l2);
        } else {
            head = l2;
            head.next = mergeList(l1, l2.next);
        }
        return head;
    }

    // 获取链表中点
    private ListNode getMedian(ListNode head, ListNode tail) {
        ListNode slow = head, fast = head;
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
